package com.ternnetwork.toolkit.service.impl.campaign;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.persistence.LockModeType;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;



import com.ternnetwork.cms.service.file.CmsFileService;
import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.commons.utils.DateUtils;
import com.ternnetwork.commons.utils.ExtendedFileUtils;
import com.ternnetwork.commons.utils.ValidateUtils;
import com.ternnetwork.persistence.page.BootstrapGrid;
import com.ternnetwork.persistence.page.Page;
import com.ternnetwork.toolkit.dao.campaign.CampaignDao;
import com.ternnetwork.toolkit.dao.campaign.CampaignChannelDao;
import com.ternnetwork.toolkit.dao.campaign.CampaignDataDao;
import com.ternnetwork.toolkit.enums.CampaignType;
import com.ternnetwork.toolkit.model.campaign.Campaign;
import com.ternnetwork.toolkit.model.campaign.CampaignChannel;
import com.ternnetwork.toolkit.model.campaign.CampaignData;
import com.ternnetwork.toolkit.model.campaign.CampaignDataRequest;
import com.ternnetwork.toolkit.service.campaign.CampaignDataService;



@Service("campaignDataService")
public class CampaignDataServiceImpl implements CampaignDataService {
	
	@Resource
	private CampaignDataDao campaignDataDao;
	
	@Resource
	private CampaignDao campaignDao;

	@Resource
	private CampaignChannelDao campaignChannelDao;
	
	@Resource
	private CmsFileService cmsFileService;
	
	
	
	private Boolean isWechat(HttpServletRequest request){
		String ua = request.getHeader("user-agent").toLowerCase();
		if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
			return true;
		}
		return false;
	}
	
	
	public  BaseResponse idoAdd(CampaignDataRequest CampaignDataRequest){
		
	    	BaseResponse res=new BaseResponse();
	    	
	    	if(StringUtils.isEmpty(CampaignDataRequest.getCampaignCode())){
	       		res.setStatus(0);
	       		res.setMessage("操作失败,campaignCode不能为空！");
	    		return res;
	    	}
	    	if(StringUtils.isEmpty(CampaignDataRequest.getChannelCode())){
	       		res.setStatus(1);
	       		res.setMessage("操作失败,channelCode不能为空！");
	    		return res;
	    	}
	    	
	    	List<Campaign> campaignList=campaignDao.findAll("from Campaign where code=?1", CampaignDataRequest.getCampaignCode());
	        if(campaignList.size()==0){
	        	res.setStatus(2);
	       		res.setMessage("操作失败,campaignCode不存在！");
	    		return res;
	        }
	        Campaign infoCollectionCampaign=campaignList.get(0);
	        Date currentTime=new Date();
	        if(infoCollectionCampaign.getStartTime().getTime()>currentTime.getTime()){
	        	res.setStatus(3);
	       		res.setMessage("操作失败,活动未开始！");
	    		return res;
	        }
	        if(infoCollectionCampaign.getEndTime().getTime()<currentTime.getTime()){
	        	res.setStatus(4);
	       		res.setMessage("操作失败,活动已结束！");
	    		return res;
	        }
	        
	       	List<CampaignChannel> channelList=campaignChannelDao.findAll("from CampaignChannel where code=?1", CampaignDataRequest.getChannelCode());
	        if(channelList.size()==0){
	        	res.setStatus(5);
	       		res.setMessage("操作失败,channelCode不存在！");
	    		return res;
	        }
	        
	    	for(CampaignData t:CampaignDataRequest.getDataList()){
	    		
	    		
	    		if(infoCollectionCampaign.getType().equals(CampaignType.TYPE_1)||infoCollectionCampaign.getType().equals(CampaignType.TYPE_2)){
	    			//活动类型为 老用户荐新  老用户再购 时需要校验老用户的手机和姓名
	    			if(StringUtils.isEmpty(t.getBuyerName())){
			       		res.setStatus(6);
			       		res.setMessage("操作失败,buyerName字段不能为空！");
			    		return res;
			    	}
	    			if(!ValidateUtils.isMobileNO(t.getBuyerMobilePhoneNo())){
			       		res.setStatus(7);
			       		res.setMessage("操作失败,buyerMobilePhoneNo字段校验失败！");
			    		return res;
			    	}
	    		}
	    		
	    	   	if(StringUtils.isEmpty(t.getPotentialBuyerName())){
		       		res.setStatus(8);
		       		res.setMessage("操作失败,potentialBuyerName字段不能为空！");
		    		return res;
		    	}
	    	   	if(StringUtils.isEmpty(t.getPotentialBuyerMobilePhoneNo())){
		    		res.setStatus(12);
		    		res.setMessage("操作失败，potentialBuyerMobilePhoneNo字段不能为空！");
		    		return res;
		    	}
		    	if(!ValidateUtils.isMobileNO(t.getPotentialBuyerMobilePhoneNo())){
		    		res.setStatus(9);
		    		res.setMessage("操作失败，potentialBuyerMobilePhoneNo字段校验失败！");
		    		return res;
		    	}
		    	if(StringUtils.isEmpty(t.getPotentialBuyProductModel())){
		    		res.setStatus(10);
		    		res.setMessage("操作失败，potentialBuyProductModel字段不能为空！");
		    		return res;
		    	}
		    	
	    	}
	    	List<CampaignData> dataList=CampaignDataRequest.getDataList();
	    	removeDuplicate(dataList);
	    	for(CampaignData t:dataList){
	    		t.setCampaign(campaignList.get(0));
	       		t.setChannel(channelList.get(0));
	    		long totalCount=campaignDataDao.getTotalCount("select count(t.id) from CampaignData t where t.potentialBuyerMobilePhoneNo=?1 and t.campaign.id=?2",t.getPotentialBuyerMobilePhoneNo(),t.getCampaign().getId());
		       	if(totalCount==0L){
			       	campaignDataDao.persist(t);
		       	}
	    	}
	       	res.setStatus(11);
	       	res.setMessage("操作成功！");
			return res;
	    }
	   
	/**
	 * 同批次潜客手机去重
	 * @param list
	 */
	public  void removeDuplicate(List<CampaignData> list){
		    Map<String,CampaignData> map=new ConcurrentHashMap<String,CampaignData>() ;
		    for(CampaignData t:list){
	            String key=t.getPotentialBuyerMobilePhoneNo();
	             map.put(key,t);
	        }
	        list.clear();
	        for(Map.Entry entry : map.entrySet()){
	        	CampaignData t=(CampaignData)entry.getValue();
	            list.add(t);
	        }
	        
	}
	   
	   public BootstrapGrid queryToBootstrapGrid(String campaignId,String channelId,String startTime,String endTime,String buyerMobilePhoneNo,String potentialBuyerMobilePhoneNo,Page page){
			Page<CampaignData> result=query(campaignId, channelId, startTime, endTime, buyerMobilePhoneNo, potentialBuyerMobilePhoneNo, page);
			BootstrapGrid grid=new BootstrapGrid(result);
			return grid;
		}
	   public Page<CampaignData> query(String campaignId,String channelId,String startTime,String endTime,String buyerMobilePhoneNo,String potentialBuyerMobilePhoneNo,Page page){
		    StringBuffer jpql=new StringBuffer("from CampaignData t where 1=1");
			List<Object> params=new ArrayList<Object>();
			if(StringUtils.isNotEmpty(campaignId)){
				params.add(Long.parseLong(campaignId));
				jpql.append(" and t.campaign.id=?"+params.size());
			}
			if(StringUtils.isNotEmpty(channelId)){
				params.add(Long.parseLong(channelId));
				jpql.append(" and t.channel.id=?"+params.size());
			}
			if(StringUtils.isNotEmpty(buyerMobilePhoneNo)){
				params.add(buyerMobilePhoneNo);
				jpql.append(" and t.buyerMobilePhoneNo=?"+params.size());
			}
			if(StringUtils.isNotEmpty(potentialBuyerMobilePhoneNo)){
				params.add(potentialBuyerMobilePhoneNo);
				jpql.append(" and t.potentialBuyerMobilePhoneNo=?"+params.size());
			}
			if(!StringUtils.isEmpty(startTime)){
				params.add(DateUtils.parseDate(startTime+" 00:00:00",DateUtils.FORMAT_DATE_TIME_DEFAULT));
				jpql.append(" and t.createTime>=?"+params.size());
			}
			if(!StringUtils.isEmpty(endTime)){
				params.add(DateUtils.parseDate(endTime+" 23:59:59",DateUtils.FORMAT_DATE_TIME_DEFAULT));
				jpql.append(" and t.createTime<=?"+params.size());
			}
			jpql.append(" order by t.id desc");
			return campaignDataDao.query("select count(t.id) "+jpql.toString(),jpql.toString(), page, params.toArray());
		}



	public BaseResponse idoDelete(Long id) {
		BaseResponse res=new BaseResponse();
		CampaignData t=campaignDataDao.findById(CampaignData.class, id, LockModeType.PESSIMISTIC_WRITE);
		if(t==null){
	          	res.setStatus(0);
	           	res.setMessage("操作失败，对象不存在！");
	    		return res;
	    }
		campaignDataDao.delete(t);
		res.setStatus(2);
	   	res.setMessage("操作成功！");
		return res;
	}
	
	
	  public List<CampaignData> queryAll(String campaignId,String channelId,String startTime,String endTime,String buyerMobilePhoneNo,String potentialBuyerMobilePhoneNo){
		    StringBuffer jpql=new StringBuffer("from CampaignData t where 1=1");
			List<Object> params=new ArrayList<Object>();
			if(StringUtils.isNotEmpty(campaignId)){
				params.add(Long.parseLong(campaignId));
				jpql.append(" and t.campaign.id=?"+params.size());
			}
			if(StringUtils.isNotEmpty(channelId)){
				params.add(Long.parseLong(channelId));
				jpql.append(" and t.channel.id=?"+params.size());
			}
			if(StringUtils.isNotEmpty(buyerMobilePhoneNo)){
				params.add(buyerMobilePhoneNo);
				jpql.append(" and t.buyerMobilePhoneNo=?"+params.size());
			}
			if(StringUtils.isNotEmpty(potentialBuyerMobilePhoneNo)){
				params.add(potentialBuyerMobilePhoneNo);
				jpql.append(" and t.potentialBuyerMobilePhoneNo=?"+params.size());
			}
			if(!StringUtils.isEmpty(startTime)){
				params.add(DateUtils.parseDate(startTime+" 00:00:00",DateUtils.FORMAT_DATE_TIME_DEFAULT));
				jpql.append(" and t.createTime>=?"+params.size());
			}
			if(!StringUtils.isEmpty(endTime)){
				params.add(DateUtils.parseDate(endTime+" 23:59:59",DateUtils.FORMAT_DATE_TIME_DEFAULT));
				jpql.append(" and t.createTime<=?"+params.size());
			}
			jpql.append(" order by t.id desc");
			return campaignDataDao.findAll(jpql.toString(),params.toArray());
		}
	
	
	  public List<CampaignData> queryAll(String campaignId,String startTime,String endTime){
		  return queryAll(campaignId, "", startTime, endTime, "", "");
	  }
	  
	  
	  public HSSFWorkbook exportExcel(String campaignId,String channelId,String startTime,String endTime,String buyerMobilePhoneNo,String potentialBuyerMobilePhoneNo){
		 return createExcel(queryAll(campaignId, channelId, startTime, endTime, buyerMobilePhoneNo, potentialBuyerMobilePhoneNo));
	  }
			  
	  
	
	public HSSFWorkbook createExcel(List<CampaignData> list){
		String[] header={"车主姓名","车主性别","车主手机","车主省份","车主城市","车主经销商","购车时间","所购车型","VIN","潜客姓名","潜客性别","潜客手机","潜客所在省","潜客所在市","潜客所在经销商","潜在购车车型","潜在购车预算","潜在购车时间","所属活动","所属渠道","创建时间","上传文件路径","微信ID"};
		HSSFWorkbook wb = new HSSFWorkbook(); // create new workbook object
	    HSSFSheet sheet = wb.createSheet(); // create new sheet for workbook
	    HSSFRow row;
	    HSSFCell cell;
	    row = sheet.createRow(0);
	    for(int i=0;i<header.length;i++){
	   	 cell=row.createCell((short)i);
	   	 cell.setCellValue(header[i]);
	    }
	   	for(int i=0;i<list.size();i++){
		    row = sheet.createRow((short) i + 1); // create new row for
		    CampaignData t=list.get(i);
			for(int j=0;j<header.length;j++){
				cell =row.createCell((short) (j));
		        if(j==0){
		        	cell.setCellValue(t.getBuyerName()==null?"":t.getBuyerName());	
		        }else if(j==1){
		        	cell.setCellValue(t.getBuyerGenderName()==null?"":t.getBuyerGenderName());	
		        }else if(j==2){
		        	cell.setCellValue(t.getBuyerMobilePhoneNo()==null?"":t.getBuyerMobilePhoneNo());
		        }else if(j==3){
		        	cell.setCellValue(t.getBuyerProvince()==null?"":t.getBuyerProvince());	
		        }else if(j==4){
		        	cell.setCellValue(t.getBuyerCity()==null?"":t.getBuyerCity());
		        }else if(j==5){
		        	cell.setCellValue(t.getBuyerDealer()==null?"":t.getBuyerDealer());
		        }else if(j==6){
		        	cell.setCellValue(t.getBuyTime()==null?"":t.getBuyTime());
		        }else if(j==7){
		        	cell.setCellValue(t.getPurchasedProductModel()==null?"":t.getPurchasedProductModel());	
		        }else if(j==8){
		        	cell.setCellValue(t.getPurchasedProductSerialNumber()==null?"":t.getPurchasedProductSerialNumber());	
		        }else if(j==9){
		        	cell.setCellValue(t.getPotentialBuyerName()==null?"":t.getPotentialBuyerName());	
		        }else if(j==10){
		        	cell.setCellValue(t.getPotentialBuyerGenderName()==null?"":t.getPotentialBuyerGenderName());	
		        }else if(j==11){
		        	cell.setCellValue(t.getPotentialBuyerMobilePhoneNo()==null?"":t.getPotentialBuyerMobilePhoneNo());
		        }else if(j==12){
		        	cell.setCellValue(t.getPotentialBuyerProvince()==null?"":t.getPotentialBuyerProvince());	
		        }else if(j==13){
		        	cell.setCellValue(t.getPotentialBuyerCity()==null?"":t.getPotentialBuyerCity());	
		        }else if(j==14){
		        	cell.setCellValue(t.getPotentialBuyerDealer()==null?"":t.getPotentialBuyerDealer());	
		        }else if(j==15){
		        	cell.setCellValue(t.getPotentialBuyProductModel()==null?"":t.getPotentialBuyProductModel());	
		        }else if(j==16){
		        	cell.setCellValue(t.getPotentialBuyBudget()==null?"":t.getPotentialBuyBudget());
		        }else if(j==17){
		        	cell.setCellValue(t.getPotentialBuyTime()==null?"":t.getPotentialBuyTime());
		        }else if(j==18){
		        	cell.setCellValue(t.getCampaignName());
		        }else if(j==19){
		        	cell.setCellValue(t.getChannelName());
		        }else if(j==20){
		        	cell.setCellValue(DateUtils.format(t.getCreateTime(), DateUtils.FORMAT_DATE_TIME_DEFAULT));
		        }else if(j==21){
		        	cell.setCellValue(t.getFileUrl());
		        }else if(j==22){
		        	cell.setCellValue(t.getWechatId());
		        }
			}
		}
	   	return wb;
	}
	
	 public BaseResponse upload(MultipartFile[] file, String currentDir, String dir,HttpServletRequest request) {
			BaseResponse resp=new BaseResponse();
		    if (currentDir == null) {
		    	resp.setStatus(0);
		    	resp.setMessage("操作失败,当前目录为空！");
		    	return resp;
		    }
		    if (currentDir.charAt(currentDir.length()-1) == '\\') {
				currentDir = currentDir.substring(0, currentDir.length()-1) + "/";
			} else if (currentDir.charAt(currentDir.length()-1) != '/') {
				currentDir += "/";
			}
			try{
			currentDir = java.net.URLDecoder.decode(currentDir, "UTF-8");
			String realPath=request.getSession().getServletContext().getRealPath("/");
			//定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("file", "csv");
			
			if(!ServletFileUpload.isMultipartContent(request)){
				resp.setStatus(0);
		    	resp.setMessage("操作失败,请选择文件！");
		    	return resp;
			}
			if (dir == null) {
				dir = "image";
			}
			if(!extMap.containsKey(dir)){
				resp.setStatus(0);
				resp.setMessage("操作失败,非法的文件类型！");
		    	return resp;
			}
			if(cmsFileService.checkPermitPath(request, realPath+currentDir)==false){
				resp.setStatus(0);
				resp.setMessage("操作失败,非法的上传目录！");
		    	return resp;
			}
			ExtendedFileUtils.makeDirs(realPath+currentDir);
			BufferedInputStream bis = null;      
			BufferedOutputStream bos = null; 
				 for(int i = 0,size = file.length;i<size;i++){      
						MultipartFile multipartFile = file[i];  
						String uploadFileName=multipartFile.getOriginalFilename().replace(" ","");
				    	if(!cmsFileService.checkUploadFileType(uploadFileName, extMap.get(dir))){
				    		resp.setStatus(0);
							resp.setMessage("操作失败,非法的文件格式！");
					    	return resp;
				    	}
				    	    bis = new BufferedInputStream(multipartFile.getInputStream());  
					        bos = new BufferedOutputStream(new FileOutputStream(new File(realPath+currentDir,System.currentTimeMillis()+"_"+uploadFileName)));      
					        Streams.copy(bis, bos, true);
				 }
				
				resp.setStatus(1);
				resp.setMessage("操作成功！");
		    	return resp;
	      } catch (Exception e) {      
	      	    resp.setStatus(0);
				resp.setMessage(e.getMessage());
		    	return resp;
	      }
		}
	 
   
}
